'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigQq, IDifference } from '@/interfaces';
import { updateQqConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigQq({
  source,
  translatedFields,
}: {
  source: IConfigQq;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    enable?: boolean;
    clientId?: string;
    clientSecret?: string;
    redirectUri?: string;
    state?: string;
  }>({
    enable: source.enable ?? false,
    clientId: source.clientId ?? '',
    clientSecret: '',
    redirectUri: source.redirectUri ?? '',
    state: source.state ?? '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateQqConfigMutation = useMutation(updateQqConfig);

  useEffect(() => {
    const diffData = diff(
      {
        enable: source.enable ?? false,
        clientId: source.clientId ?? '',
        clientSecret: '',
        redirectUri: source.redirectUri ?? '',
        state: source.state ?? '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      await updateQqConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateQqConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'enable') {
      setForm({ ...form, enable: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.qq.tips}
          </label>

          <ol>
            <li>
              <span className="me-2">{translatedFields.config.qq.qq}，</span>
              <a
                target="_blank"
                href="https://connect.qq.com/manage.html#/"
                rel="noreferrer"
              >
                https://connect.qq.com
              </a>
            </li>
            <li>
              <span className="me-2">
                {translatedFields.config.qq.redirectUri}，
              </span>
              <a target="_blank" href="#" rel="noreferrer">
                https://{translatedFields.config.qq.domain}/qq
              </a>
            </li>
            <li>{translatedFields.config.qq.interface}</li>
            <li>{translatedFields.config.qq.stateValue}</li>
          </ol>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.qq.enable}
          </label>
          <select
            name="enable"
            value={form.enable + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enable"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.qq.clientId}
          </label>
          <input
            type="text"
            className="form-control"
            name="clientId"
            value={form.clientId}
            onChange={onChangeForm}
            aria-describedby="clientId"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.qq.clientSecret}
          </label>
          <input
            type="password"
            className="form-control"
            name="clientSecret"
            autoComplete="password"
            value={form.clientSecret}
            onChange={onChangeForm}
            aria-describedby="clientSecret"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.qq.redirectUri}
          </label>
          <input
            type="text"
            className="form-control"
            name="redirectUri"
            value={form.redirectUri}
            onChange={onChangeForm}
            aria-describedby="redirectUri"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.qq.state}
          </label>
          <input
            type="text"
            className="form-control"
            name="state"
            value={form.state}
            onChange={onChangeForm}
            aria-describedby="state"
          />
        </div>

        <button
          type="submit"
          disabled={updateQqConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateQqConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
